package com.visionork.android.twe.model;

import java.net.URL;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class DramaRepository extends RepositoryBase {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected static final String PREFIX = "http://sugoideas.com/";
	protected static final String[] URL_LIST = {
			"http://sugoideas.com/search/2011drama",
			"http://sugoideas.com/search/2010drama",
			"http://sugoideas.com/search/2009drama",
	/*
	 * "http://sugoideas.com/search/2008drama",
	 * "http://sugoideas.com/search/2007drama",
	 * "http://sugoideas.com/search/2006drama",
	 * "http://sugoideas.com/search/2005drama",
	 * "http://sugoideas.com/search/2004drama",
	 * "http://sugoideas.com/search/2003drama",
	 * "http://sugoideas.com/search/2002drama",
	 * "http://sugoideas.com/search/2001drama"
	 */};

	@Override
	public void Crawl() {
		ArrayList<Program> tmpPrograms = new ArrayList<Program>();
		for (String urlString : URL_LIST) {
			parseUrl(tmpPrograms, urlString);
		}
		mergeProgram(tmpPrograms);
		return;
	}

	protected void parseUrl(ArrayList<Program> tmpPrograms, String urlString) {
		try {
			Document doc = Jsoup.parse(new URL(urlString), 5000);
			Elements elms = doc.getElementsByTag("div");
			for (Element elm : elms) {
				if (elm.hasAttr("class")
						&& elm.attr("class").equals("postsearch")) {
					Program program = parseProgram(elm);
					if (program != null) {
						tmpPrograms.add(program);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Program parseProgram(Element elm) {
		String title = null;
		String urlLink = null;
		String hosts = null;
		Elements hrefElms = elm.getElementsByTag("a");
		if (hrefElms != null && hrefElms.size() == 1) {
			Elements imgElms = hrefElms.get(0).getElementsByTag("img");
			if (imgElms != null && imgElms.size() == 1) {

				title = imgElms.get(0).attr("title");
				String[] stringParts = title.split("/");
				title = stringParts[stringParts.length - 1].trim();
				urlLink = hrefElms.get(0).attr("href");

			}
		}

		Elements hostElms = elm.getElementsByTag("span");
		for (Element hostElm : hostElms) {
			if (hostElm.hasAttr("class")
					&& hostElm.attr("class").equals("searchOne"))

			{
				hosts = hostElm.text().trim();
				break;
			}
		}

		if (urlLink != null && title != null && urlLink.startsWith(PREFIX)
				&& title.trim().length() > 0) {
			Program prog = new Program();
			prog.setTitle(title);
			prog.setUrlLink(urlLink);
			prog.setHosts(hosts);
			return prog;
		}

		return null;
	}

	@Override
	protected String getConfigFileName() {
		return "DRAMAREPOSITORY";
	}

}
